package com.kd.juhaowan.ui;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.AutoLoginApi;
import com.kd.juhaowan.http.api.CommonApi;
import com.kd.juhaowan.http.api.CreateOrderApi;
import com.kd.juhaowan.http.model.CreateOrderResult;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.PayChannel;
import com.kd.juhaowan.http.model.PlatCoinRate;
import com.kd.juhaowan.http.model.PlatCoinResult;
import com.kd.juhaowan.http.model.PlatCoinType;
import com.kd.juhaowan.http.model.PlatCoinUser;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.pay.AlipayPayOperation;
import com.kd.juhaowan.pay.WXH5PayActivity;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.utils.ResUtils;
import com.kd.juhaowan.view.AutoLoginDialog;

import java.util.List;

import butterknife.OnClick;
import okhttp3.Call;

public class PlatFormCoinActivity extends BaseActivity{


    private GridView moneyGridView;
    private BaseAdapter moneyAdapter;
    private GridView typeGridView;
    private BaseAdapter typeAdapter;
//    String[] mMoney;
    private int seletPosition = 0;
    private int typeSelecPosition = 0;
    private ImageView backImage;
    private TextView accountText,balanceText,biliText,confirmText;
    private EditText moneyEdit;
//    private Goods mGoods;
    private List<PlatCoinType> moneyList;
    private List<PayChannel> channelList;
    private PlatCoinUser myInfo;
    private PlatCoinRate mRate;
    private int number;
    private LinearLayout loginedLayout;
    private RelativeLayout unLoginLayout;


    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.hnssn_activity_platform_coin;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        mGoods = getIntent().getParcelableExtra("goods");
////        setContentView(getLayoutIdentifier("hnssn_activity_platform_coin"));
////        mMoney = new String[]{"aaaaa", "bbbbbb", "ccccc", "dddd", "ffff"};
        moneyGridView = findViewById(getViewIdentifier("platform_coin_money_gird"));
        typeGridView = findViewById(getViewIdentifier("platform_coin_type_gird"));
        accountText = findViewById(getViewIdentifier("platform_coin_account"));
        balanceText = findViewById(getViewIdentifier("platform_coin_money"));
        biliText = findViewById(getViewIdentifier("platform_coin_bili"));
        confirmText = findViewById(getViewIdentifier("platform_coin_confirm"));
        moneyEdit = findViewById(getViewIdentifier("login_account_account"));
        loginedLayout = findViewById(getViewIdentifier("platfrom_logined_layout"));
        unLoginLayout = findViewById(getViewIdentifier("platform_unlogin_layout"));
        backImage = findViewById(getViewIdentifier("platform_coin_close"));
        moneyEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.e("PlatFormCoinActivity","onFocusChange"+hasFocus);
                if(hasFocus){
//                    seletPosition= -1;
//                    moneyAdapter.notifyDataSetChanged();
//                    confirmText.setText("确认支付 ￥");
//                    number = 0;
                }
            }
        });
        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString().toString();
                if(moneyEdit.isFocused()){
                    if(!TextUtils.isEmpty(temp)){
                        number = Integer.parseInt(temp);
                        confirmText.setText("确认支付 ￥"+number/mRate.getData());
                    }else{
                        if(seletPosition!=-1){
                            number = moneyList.get(seletPosition).getCurrency();
                            confirmText.setText("确认支付 ￥"+number/mRate.getData());
                        }
                    }
                }

            }
        });
        confirmText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mGoods.setGoodsPrice(number/mRate.getData());
                String type = channelList.get(typeSelecPosition).getId();
                EasyHttp.post(PlatFormCoinActivity.this).api(new CreateOrderApi(number+"",type)).request(new HttpCallbackProxy<HttpData<CreateOrderResult>>(PlatFormCoinActivity.this){
                    @Override
                    public void onHttpSuccess(HttpData<CreateOrderResult> result, boolean cache) {
                        super.onHttpSuccess(result, cache);
                        CreateOrderResult orderResult= result.getData();
                        if(orderResult.getOpen_with()==3){
                            alipayPayV1(orderResult.getPayinfo());
                        }else if (orderResult.getOpen_with()==2){
                            webH5Pay(orderResult.getPayinfo());
                        }else{
                            startDefaultWebBrowser(orderResult.getPayinfo());
                        }

                    }
                });
//                SimpleAsyncResponseHandler handler = requestCallbackHandler(CreateOrderResponseParams.class, type);
//                mCreateOrderTaskId = HttpEngineApi.getInstance().createPlatCoinOrder(type, mGoods,number+"", handler);

            }
        });

        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(getViewIdentifier("platform_coin_detail")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myInfo==null)return;
                Intent intent = new Intent(PlatFormCoinActivity.this,PlatFormCoinDetailActivity.class);
                intent.putExtra("info",myInfo);
                register.launch(intent);
//                startActivity(intent);
            }
        });
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtil.debugLog( "onActivityResult: _____" + result);
                if (result != null) {

                    if (result.getResultCode() == Activity.RESULT_OK) {
                        initData();

                    }
                }
            }
        });


        if(getIntent().getBooleanExtra("isPay",false)){
            String userName = getIntent().getStringExtra("username");
            String avatar = getIntent().getStringExtra("avatar");
            List<LoginUser> infos = manager.readAllUserAccountInfo();
            if(infos.size()>0){
                LoginUser user = infos.get(0);
                if(user.getAccount().equals(userName)){
                    AutoLoginDialog dialog = new AutoLoginDialog(PlatFormCoinActivity.this,user.getAccount());
                    dialog.show();
                    EasyHttp.post(this).api(new AutoLoginApi(user.getRefresh_token())).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
                        @Override
                        public void onHttpSuccess(HttpData<LoginUser> result, boolean cache) {
                            super.onHttpSuccess(result, cache);
                            LoginUser loginUser = result.getData();
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                            user.setAccess_token(loginUser.getAccess_token());
                            user.setRefresh_token(loginUser.getRefresh_token());
                            manager.saveUserAccount(user);
                            manager.writeAutoLogin(true);
                            manager.writeLastLoginType(1);
                            manager.saveCurrentLoginUserTickit(user.getAccess_token());
//                    cancelLoadingDialog();

                            initData();
                        }

                        @Override
                        public void onHttpEnd(Call call) {
                            super.onHttpEnd(call);
                            dialog.dismiss();
                        }
                    });
                }else{
                    LoginUser myuser =null;
                    for (LoginUser info:infos) {
                        if(info.getAccount().equals(userName)&&!info.isPhoneAccount()){
                            myuser = info;
                            break;
                        }
                    }
                    if(myuser!=null){
                        Intent intent = new Intent(PlatFormCoinActivity.this,ChangeAccountActivity.class);
                        intent.putExtra("username",userName);
                        intent.putExtra("avatar",avatar);
                        register.launch(intent);
                    }else{
                        Intent intent = new Intent(PlatFormCoinActivity.this,LoginAccountActivity.class);
                        intent.putExtra("isPay",true);
                        intent.putExtra("username",userName);
                        intent.putExtra("avatar",avatar);
                        register.launch(intent);
                    }
                }
            }else{
                Intent intent = new Intent(PlatFormCoinActivity.this,LoginAccountActivity.class);
                intent.putExtra("isPay",true);
                intent.putExtra("username",userName);
                intent.putExtra("avatar",avatar);
                register.launch(intent);

            }
        }else{
            initData();
        }
    }
    private ActivityResultLauncher<Intent> register;

    @Override
    protected void reInitDate() {
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();


//        initData();
//        moneyEdit.setText("");
    }

    @OnClick(R.id.mine_name)
    public void gotoLogin(View view){
        if(myInfo==null){
            manager.writeAutoLogin(false);
            baseRegister.launch(new Intent(PlatFormCoinActivity.this,LoginAccountActivity.class));
        }
//        startActivity(new Intent(getActivity(), PlatFormCoinActivity.class));
    }

    private int mGetPayChannelTaskId,mCreateOrderTaskId;
    private void initData(){
        EasyHttp.post(this).api(new CommonApi("api/ptb/index")).request(new HttpCallbackProxy<HttpData<PlatCoinResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<PlatCoinResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);

                moneyList = result.getData().getCurrencyList();
                channelList = result.getData().getPayList();
                myInfo = result.getData().getCurrencyUser();
                mRate = result.getData().getProportion();

                setData();
            }
        });
    }
//
//    @Override
//    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
//        super.onAsyncRequestResult(flag, response, params);
//        if (flag == mCreateOrderTaskId) {
//
//            executeCreateOrderResult(response, PayType.valueOf((int)params[0]));
//        }else if (flag == mGetPayChannelTaskId){
//            PlatFormCoinResponseParams responseParams = (PlatFormCoinResponseParams) response;
//            if (State.SUCCESS == responseParams.getState().getCode()) {
//                moneyList = responseParams.getData().getCurrencyList();
//                channelList = responseParams.getData().getPayList();
//                myInfo = responseParams.getData().getCurrencyUser();
//                mRate = responseParams.getData().getProportion();
//                setData();
//            }
//        }
//
//    }
//
//    private void executeCreateOrderResult(ResponseParams response, PayType payType) {
//        if (response instanceof CreateOrderResponseParams) {
//            CreateOrderResponseParams responseParams = (CreateOrderResponseParams) response;
//            if (State.SUCCESS == responseParams.getState().getCode()) {
//                switch (payType) {
//                    case WEIXIN_PAY:
//                        weixinPay(responseParams.getData());
//                        break;
//
//                    case WEIXIN_APPLET_PAY:
//                        weixinAppletPay(responseParams.getData());
//                        break;
//
//                    case ALIPAY_PAY:
//                    case HAOGE_PAY:
//                        alipayPayV1(responseParams.getData());
//                        break;
//
//                    case UNION_PAY:
//                    case PAYPAL_PAY:
//                    case LEYUN_PAY:
//                    case UNDER_LINE_PAY:
//                        webH5Pay(responseParams.getData());
//                        break;
//                    case WECHAT_APP_PAY:
//                        weixinAppPay(responseParams.getData());
//                        break;
//                    case DEFAULT_WEB_BROWSER:
//                        startDefaultWebBrowser(responseParams.getData());
//                        break;
//
//
//
//                    default:
//                        DialogFactory.createConfirmDialog(this, getString(getStringIdentifier("hnssn_hint_payerror"))).show();
//                }
//            }
//        }
//    }
//
    private void alipayPayV1(String payInfo) {
        Log.d("alipay","alipayPayV1");

            new AlipayPayOperation(this).execute(payInfo);

    }

    public void reFreshDate(){
        this.onResume();
    }
//    private void weixinAppletPay(CreateOrderResponseParams.CreateOrderResponseData response) {
//        if (response != null) {
//            Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_WECHAT_APPLET_PAY);
//            intent.setPackage(getPackageName());
//            intent.putExtra("wechat_applet_pay_info", response.getPay_info());
//            startActivityForResult(intent, APPLET_REQUEST_CODE);
//        }
//    }
    private static final int START_DEFAULT_BROWSER_REQUEST_CODE = 0x0003;
    private static final int REQUEST_CODE = 0x0000;
//    private static final int APPLET_REQUEST_CODE = 0x0001;
    private void startDefaultWebBrowser(String response) {

        if (!TextUtils.isEmpty(response)) {
            try {
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(response)), START_DEFAULT_BROWSER_REQUEST_CODE);
            } catch (ActivityNotFoundException exception) {
                exception.printStackTrace();
                Toast.makeText(getApplicationContext(), "浏览器打开异常", Toast.LENGTH_SHORT).show();

            }
        } else {

        }
    }
//
//    private void weixinPay(CreateOrderResponseParams.CreateOrderResponseData response) {
//        if (response != null) {
//            int type = 0;
//            if (ToolsUtils.checkNumber(response.getType())) {
//                type = Integer.parseInt(response.getType());
//            }
//            webH5Pay(response);
////            switch (type) {
////                case 2:
////                    HeepayPayOperation.pay(this, response.getPay_info(), response.getOrder_no());
////                    break;
////                default:
////                    webH5Pay(response);
////            }
//        }
//    }
//    private void weixinAppPay(CreateOrderResponseParams.CreateOrderResponseData response) {
//        if (response != null) {
//            WeChatOperation.getInstance().startWeChatApplet(PlatFormCoinActivity.this,response.getPay_info());
//        }
//    }
    private void webH5Pay(String url) {
        Intent intent = new Intent(this, WXH5PayActivity.class);
        intent.setPackage(getPackageName());
        intent.putExtra("weixinPay", url);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("CoinActivity",requestCode+"..requestCode"+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(getApplicationContext(),"充值成功", Toast.LENGTH_SHORT).show();
            initData();
        }
    }

    private void setData(){
        if(myInfo!=null){
            unLoginLayout.setVisibility(View.GONE);
            loginedLayout.setVisibility(View.VISIBLE);
            confirmText.setVisibility(View.VISIBLE);
            accountText.setText("充值账号："+myInfo.getUsername());
            balanceText.setText(myInfo.getCurrency());
        }
        biliText.setText("（"+mRate.getName()+"）");
        number = moneyList.get(seletPosition).getCurrency();
        confirmText.setText("确认支付 ￥"+moneyList.get(seletPosition).getCurrency()/mRate.getData());
        initAdapter();
    }
//
//
    private void initAdapter(){
        if(moneyAdapter==null) {
            moneyAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return moneyList == null ? 0 : moneyList.size();
                }

                @Override
                public Object getItem(int position) {
                    return moneyList.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    MoneyViewHolder viewHolder;
                    if (convertView == null) {
                        viewHolder = new MoneyViewHolder();
                        final Context context = parent.getContext();
                        LayoutInflater inflater = LayoutInflater.from(context);
                        final int layoutResId = ResUtils.getLayoutIdentifier(context, "hnssn_item_platform_money");
                        final int titleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_title");
                        final int subtitleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_subtitle");
                        final int bgResId = ResUtils.getViewIdentifier(context, "item_platformcoin_bg");
                        convertView = inflater.inflate(layoutResId, parent, false);
                        viewHolder.title = convertView.findViewById(titleResId);
                        viewHolder.subTitle = convertView.findViewById(subtitleResId);
                        viewHolder.backView = convertView.findViewById(bgResId);
                        convertView.setTag(viewHolder);
                    } else {
                        viewHolder = (MoneyViewHolder) convertView.getTag();
                    }
                    PlatCoinType money = moneyList.get(position);
                    viewHolder.title.setText(money.getCurrency() + "个");
                    if (money.getGive() == 0) {
                        viewHolder.subTitle.setVisibility(View.GONE);
                    } else {
                        viewHolder.subTitle.setVisibility(View.VISIBLE);
                        viewHolder.subTitle.setText(money.getGiveText());
                    }
                    if (position == seletPosition) {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hnssn_bg_platformcoin_money_select"));
                        viewHolder.title.setTextColor(getColor(R.color.c60));
                    } else {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hn669_platformcoin_edit_bg"));
                        viewHolder.title.setTextColor(Color.parseColor("#333333"));
                    }
                    return convertView;
                }
            };
            moneyGridView.setAdapter(moneyAdapter);
            moneyGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    seletPosition = position;
                    moneyAdapter.notifyDataSetChanged();
                    moneyEdit.setText("");
                    number = moneyList.get(seletPosition).getCurrency();
                    confirmText.setText("确认支付 ￥" + number / mRate.getData());
                }
            });
        }else{
            moneyAdapter.notifyDataSetChanged();
        }
        if(typeAdapter==null) {
            typeAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return channelList == null ? 0 : channelList.size();
                }

                @Override
                public Object getItem(int position) {
                    return channelList.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    TypeViewHolder viewHolder;
                    if (convertView == null) {
                        viewHolder = new TypeViewHolder();
                        final Context context = parent.getContext();
                        LayoutInflater inflater = LayoutInflater.from(context);
                        final int layoutResId = ResUtils.getLayoutIdentifier(context, "hnssn_item_platform_type");
                        final int titleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_title");
                        final int subtitleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_icon");
                        final int bgResId = ResUtils.getViewIdentifier(context, "item_platformcoin_bg");
                        convertView = inflater.inflate(layoutResId, parent, false);
                        viewHolder.title = convertView.findViewById(titleResId);
                        viewHolder.icon = convertView.findViewById(subtitleResId);
                        viewHolder.backView = convertView.findViewById(bgResId);
                        convertView.setTag(viewHolder);
                    } else {
                        viewHolder = (TypeViewHolder) convertView.getTag();
                    }
                    PayChannel channel = channelList.get(position);
                    viewHolder.title.setText(channel.getName());

                    GlideHelper.loadGoodsCover(Glide.with(viewHolder.icon), viewHolder.icon,channel.getIcon());

                    if (position == typeSelecPosition) {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hnssn_bg_platformcoint_type_select"));
//                    viewHolder.title.setTextColor(Color.parseColor("#1D97FD"));
                    } else {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hn669_platformcoin_edit_bg"));
//                    viewHolder.title.setTextColor(Color.parseColor("#333333"));
                    }
                    return convertView;
                }
            };
            typeGridView.setAdapter(typeAdapter);
            typeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    typeSelecPosition = position;
                    typeAdapter.notifyDataSetChanged();
                }
            });
        }else {
            typeAdapter.notifyDataSetChanged();
        }

    }

    public static class MoneyViewHolder {
        public TextView title;
        public TextView subTitle;
        private LinearLayout backView;
    }
    public static class TypeViewHolder {
        public TextView title;
        public ImageView icon;
        private LinearLayout backView;
    }
}
